<?php

require_once 'Pipes/Value/Template/CamelCapsToDatabase.php';

class Pipes_Database_RelationshipTable
{
	private $_nameOne = null;
	private $_nameTwo = null;
	private $_relationshipName = '';
	private $_exists = false;
	private $_pdo = null;

	public function __construct(PipesImpl_Config $config, $nameOne, $nameTwo) {
		$this->_nameOne = new Pipes_Value_Template_CamelCapsToDatabase($nameOne);
		$this->_nameTwo = new Pipes_Value_Template_CamelCapsToDatabase($nameTwo);

		$this->_relationshipName = "{$this->_nameOne->value}s_to_{$this->_nameTwo->value}s";
		
		$this->_pdo = $config->pdo;
		$statement = $this->_pdo->query("SHOW TABLES LIKE '{$this->_relationshipName}'");
		
		if ($statement->fetch() !== false) {
			$this->_exists = true;
		}
	}

	public function exists() {
		return $this->_exists;
	}

	public function create() {
		$this->_pdo->query("
			CREATE TABLE {$this->_relationshipName} (
				{$this->_nameOne->value}_id INT NOT NULL,
				{$this->_nameTwo->value}_id INT NOT NULL,
				PRIMARY KEY (`{$this->_nameOne->value}_id`, `{$this->_nameTwo->value}_id`)
			)"
		);

		$this->_exists = true;
	}
}
